import type { App } from 'vue';
import { createRouter, createWebHashHistory, createWebHistory } from 'vue-router';

import { convertToRouteRecordRaw, routes } from './modules';

import { useAuthStore } from '../store';

const { VITE_HASH_ROUTE = 'N', VITE_BASE_URL } = import.meta.env;
let authStore: any;

/** 初始化创建路由 */
export const router = createRouter({
    history:
        VITE_HASH_ROUTE === 'Y'
            ? createWebHashHistory(VITE_BASE_URL)
            : createWebHistory(VITE_BASE_URL),
    routes: routes.map((route) => convertToRouteRecordRaw(route))
});

/** 安装vue路由 */
export async function setupRouter(app: App) {
    app.use(router);
    await router.isReady();
}

/** 路由判断权限跳转 */
router.beforeEach((to, from, next) => {
    if (to.meta.title) {
        // @ts-ignore
        window.document.title = to.meta.title;
    }
    // 每次路由切换查询用户信息
    if (!authStore) {
        authStore = useAuthStore();
    }
    if (authStore.isLogin) {
        authStore.updateUserInfo();
    }
    if (to.matched.some((record) => record.meta.requiredLogin)) {
        next();
    } else {
        next();
    }
});
